#include "qpropertybaseeditor.h"

#include "../sharedlib/qabstractproperty.h"

#include <QIcon>
#include <QHBoxLayout>
#include <QPainter>
#include <QEvent>
#include <QApplication>

using namespace CORELIB;

QPropertyBaseEditor::QPropertyBaseEditor(SHAREDLIB::QAbstractProperty *pro, QWidget *parent) :
    QWidget(parent),
    m_property(pro)
{
    this->setFocusPolicy(Qt::StrongFocus);
    m_old_value=pro->getValue();
    m_resetButton=new QToolButton;
    m_resetButton->setIcon(QIcon(":/images/reset.png"));
    m_resetButton->setIconSize(QSize(8,8));
    m_resetButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::MinimumExpanding));

    connect(m_property,SIGNAL(attributeChanged(QString)),this,SLOT(propertyModified(QString)));

    connect(m_resetButton,SIGNAL(clicked()),this,SLOT(reset()));

    this->setProperty("no-ManhattanStyle",true);
}

void QPropertyBaseEditor::setEditorWidget(QWidget *wid)
{
    QHBoxLayout *h=new QHBoxLayout;
    this->setLayout(h);
    h->setContentsMargins(0,0,0,0);
    h->setSpacing(0);
    h->addWidget(wid);
    h->addWidget(m_resetButton);
    this->setFocusProxy(wid);
    wid->installEventFilter(this);
    m_widget=wid;
}

void QPropertyBaseEditor::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    p.fillRect(this->rect(),Qt::white);
}

void QPropertyBaseEditor::enabledButton(bool enable)
{
    m_resetButton->setEnabled(enable);
}

void QPropertyBaseEditor::reset()
{
    m_property->setSignalValue(m_property->getDefaultValue());
    m_property->setModified(false);
    enabledButton(false);
}

void QPropertyBaseEditor::setText(const QString text)
{
    m_text=text;
}

QString QPropertyBaseEditor::text()
{
    return m_property->valueText();
}

void QPropertyBaseEditor::setReset(bool b)
{
    m_resetButton->setVisible(b);
}

void QPropertyBaseEditor::propertyModified(const QString &key)
{
    if(key=="modified")
    {
        m_resetButton->setEnabled(m_property->attribute(key).toBool());
    }
}

QVariant QPropertyBaseEditor::get_old_value()
{
    return m_old_value;
}

SHAREDLIB::QAbstractProperty* QPropertyBaseEditor::get_property()
{
    return m_property;
}

bool QPropertyBaseEditor::eventFilter(QObject *o, QEvent *e)
{
    if(o==m_widget && e->type()==QEvent::FocusOut)
    {
        qApp->sendEvent(this,e);
    }
    return QWidget::eventFilter(o,e);
}
